﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Security.Cryptography;
using System.Text;
using CodeContrib.Data.Entity;

namespace CodeContribBlog.Data
{
	[MetadataType(typeof (UserMetadata))]
	public class User : Entity
	{
		private const string _constantSalt = "xi07cevs01q4#"; // TODO Change to something else.

		public string EmailAddress { get; set; }
		public string HashedPassword { get; private set; }
		public string Name { get; set; }
		public string PasswordSalt { get; private set; }
		public string TwitterUsername { get; set; }

		public User()
		{
			PasswordSalt = Guid.NewGuid().ToString("N");
		}

		private string GetHashedPassword(string password)
		{
			using (var sha526 = SHA256.Create())
			{
				var computedHash = sha526.ComputeHash(Encoding.Unicode.GetBytes(PasswordSalt + password + _constantSalt));

				return Convert.ToBase64String(computedHash);
			}
		}

		public User SetPassword(string password)
		{
			HashedPassword = GetHashedPassword(password);

			return this;
		}

		public bool ValidatePassword(string password)
		{
			return HashedPassword == null || HashedPassword == GetHashedPassword(password);
		}
	}
}